package com.zzl.finance.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzl.finance.data.constant.AccountStopStatusEnum;
import com.zzl.finance.data.constant.StringConstant;
import com.zzl.finance.data.dao.BankAccountDao;
import com.zzl.finance.data.dto.BankAccountAddDto;
import com.zzl.finance.data.dto.BankAccountUpdateDto;
import com.zzl.finance.data.dto.feign.BankAccountFeignAddDto;
import com.zzl.finance.data.entity.BankAccountEntity;
import com.zzl.finance.data.entity.EnterpriseEntity;
import com.zzl.finance.data.service.BankAccountService;
import com.zzl.finance.data.service.EnterpriseService;
import com.zzl.general.aly.AlyApiUntil;
import com.zzl.general.aly.pojo.BankAp;
import com.zzl.general.aly.pojo.BankApRecord;
import com.zzl.general.common.constant.DeletedStatusConstant;
import com.zzl.general.common.exception.SysException;
import com.zzl.general.common.serurity.entity.User;
import com.zzl.general.common.utils.PageUtils;
import com.zzl.general.common.utils.Query;
import com.zzl.general.common.utils.UuidUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hyt
 */
@Service("bankAccountService")
public class BankAccountServiceImpl extends ServiceImpl<BankAccountDao, BankAccountEntity> implements BankAccountService {

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private AlyApiUntil alyApiUntil;

    @Override
    public void saveBankAccount(BankAccountAddDto accountAddDto, User user) throws SysException {
        BankAccountEntity bankAccount = new BankAccountEntity();
        BeanUtils.copyProperties(accountAddDto, bankAccount);
        bankAccount.setCreatorId(user.getId());
        bankAccount.setOrgId(user.getOrgId());
        bankAccount.setEnterpriseId(user.getEnterpriseId());
        EnterpriseEntity enterprise = enterpriseService.getById(accountAddDto.getEnterpriseId());
        bankAccount.setEnterpriseCategory(enterprise.getCategory());
        bankAccount.setEnterpriseName(enterprise.getEnterpriseName());
        bankAccount.setAccountName(enterprise.getEnterpriseName());
        bankAccount.setCreatorId(user.getId());
        bankAccount.setId(UuidUtils.UUID());
        if (!this.save(bankAccount)) {
            throw new SysException("A00001", "保存失败！");
        }
    }

    @Override
    public String saveBankAccountFeign(BankAccountFeignAddDto accountAddDto) throws SysException {
        QueryWrapper<BankAccountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("corporate_account", accountAddDto.getCorporateAccount());
        queryWrapper.eq("enterprise_id", accountAddDto.getEnterpriseId());
        BankAccountEntity one = this.getOne(queryWrapper);
        if (one != null) {
            return one.getId();
        }
        BankAccountEntity bankAccount = new BankAccountEntity();
        BeanUtils.copyProperties(accountAddDto, bankAccount);
        if (!this.save(bankAccount)) {
            throw new SysException("A00001", "保存失败！");
        }
        return bankAccount.getId();
    }

    /**
     * 分页查询银行账户数据
     *
     * @param params 条件参数
     * @return 分页列表
     */
    @Override
    public PageUtils listWhitePage(Map<String, Object> params, User user) {
        String enterpriseId = (String) params.get("enterpriseId");
        String accountOpeningOutlet = (String) params.get("accountOpeningOutlet");
        String corporateAccount = (String) params.get("corporateAccount");
        IPage<BankAccountEntity> page = new Query<BankAccountEntity>().getPage(params);
        QueryWrapper<BankAccountEntity> queryWrapper = new QueryWrapper<>();
        Map<String, String> enterpriseIdAndName = new HashMap<>();
        if (StringUtils.isBlank(enterpriseId)) {
            if (StringConstant.ORG_GROUP.equals(user.getUserCategory())) {
                //查询6家核心企业和集团ids
                enterpriseIdAndName = enterpriseService.findCoreEnterPriseListId();
                queryWrapper.lambda().in(BankAccountEntity::getEnterpriseId, enterpriseIdAndName.keySet());
            } else {
                queryWrapper.lambda().eq(BankAccountEntity::getEnterpriseId, user.getEnterpriseId());
            }
        } else {
            queryWrapper.lambda().eq(BankAccountEntity::getEnterpriseId, enterpriseId);
        }
        if (StringUtils.isNotBlank(accountOpeningOutlet)) {
            queryWrapper.lambda().eq(BankAccountEntity::getAccountOpeningOutlet, accountOpeningOutlet);
        }
        if (StringUtils.isNotBlank(corporateAccount)) {
            queryWrapper.lambda().like(BankAccountEntity::getCorporateAccount, corporateAccount);
        }
        queryWrapper.lambda().orderByDesc(BankAccountEntity::getIsSetTop, BankAccountEntity::getUpdateTime);
        IPage<BankAccountEntity> bankAccountPage = page(page, queryWrapper);
        List<BankAccountEntity> bankAccounts = bankAccountPage.getRecords();
        if (CollectionUtils.isEmpty(bankAccounts)) {
            return new PageUtils(bankAccountPage);
        }
        if (CollectionUtils.isEmpty(enterpriseIdAndName)) {
            enterpriseIdAndName.put(user.getEnterpriseId(), enterpriseService.getById(user.getEnterpriseId()).getEnterpriseName());
        }
        Map<String, String> finalEnterpriseIdAndName = enterpriseIdAndName;
        bankAccounts.forEach(e ->
                e.setEnterpriseName(finalEnterpriseIdAndName.get(e.getEnterpriseId()))
        );
        return new PageUtils(bankAccountPage);
    }

    @Override
    public void updateBankAccount(BankAccountUpdateDto updateDto, User user) throws SysException {
        BankAccountEntity bankAccount = new BankAccountEntity();
        BeanUtils.copyProperties(updateDto, bankAccount);
        bankAccount.setUpdateTime(new Date());
        if (!this.updateById(bankAccount)) {
            throw new SysException("A00002", "修改失败！");
        }
    }

    @Override
    public List<String> getAccountOpeningOutletByLoginUser(String enterpriseId, User user) {
        QueryWrapper<BankAccountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BankAccountEntity::getEnterpriseId, enterpriseId)
                .eq(BankAccountEntity::getStopState, StringConstant.ENTERPRISE_STOP_STATUS_ENABLE)
                .eq(BankAccountEntity::getDeletedStatus, DeletedStatusConstant.DELETED_STATUS_ON.getKey());
        List<BankAccountEntity> bankAccounts = list(queryWrapper);
        if (CollectionUtils.isEmpty(bankAccounts)) {
            return new ArrayList<>();
        }
        return bankAccounts.stream().map(BankAccountEntity::getAccountOpeningOutlet).distinct().collect(Collectors.toList());
    }

    @Override
    public List<BankApRecord> getAllAccountOpeningOutlet(Map<String, Object> params, User user) throws SysException {
        List<BankApRecord> result = new ArrayList<>();
        String bank = (String) params.get("bank");
        String province = (String) params.get("province");
        String city = (String) params.get("city");
        if (StringUtils.isBlank(bank) || StringUtils.isBlank(province) || StringUtils.isBlank(city)) {
            throw new SysException("参数不能为空！");
        }
        Map<String, String> map = new HashMap<>();
        map.put("bank", bank);
        map.put("page", "1");
        map.put("province", province);
        map.put("city", city);
        BankAp bankAp = alyApiUntil.queryBankAps(map);
        if (bankAp == null) {
            throw new SysException("当前省市下无开户网点");
        }
        int totalPage = Integer.parseInt(bankAp.getTotalPage());
        if (totalPage > 5) {
            totalPage = 5;
        }
        result.addAll(bankAp.getRecord());
        for (int i = 1; i < totalPage; i++) {
            map.put("page", String.valueOf(i + 1));
            BankAp bankAp1 = alyApiUntil.queryBankAps(map);
            result.addAll(bankAp1.getRecord());
        }
        return result;
    }

    @Override
    public List<BankAccountEntity> listByEnterpriseId(String enterpriseId, User user) {
        QueryWrapper<BankAccountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BankAccountEntity::getEnterpriseId, enterpriseId)
                .eq(BankAccountEntity::getStopState, StringConstant.ENTERPRISE_STOP_STATUS_ENABLE)
                .eq(BankAccountEntity::getDeletedStatus, DeletedStatusConstant.DELETED_STATUS_ON.getKey());
        return list(queryWrapper);
    }

    @Override
    public void getLNameIsCorrect(Map<String, Object> params, User user) throws SysException {
        String lName = (String) params.get("lName");
        if (lName == null) {
            throw new SysException("请传入参数！");
        }
        Map<String, String> map = new HashMap<>();
        map.put("page", "1");
        map.put("key", lName);
        BankAp bankAp = alyApiUntil.queryBankAps(map);
        if (bankAp == null) {
            throw new SysException("网络异常，请联系管理员");
        }
        if (CollectionUtils.isEmpty(bankAp.getRecord()) || bankAp.getRecord().size() > 1 || !lName.equals(bankAp.getRecord().get(0).getLName())) {
            throw new SysException("未查询到开户网点，还请确认并修改");
        }
    }

    @Override
    public List<String> noParamsGetAccountOpeningOutletByLoginUser(User user) {
        QueryWrapper<BankAccountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BankAccountEntity::getStopState, StringConstant.ENTERPRISE_STOP_STATUS_ENABLE)
                .eq(BankAccountEntity::getDeletedStatus, DeletedStatusConstant.DELETED_STATUS_ON.getKey());
        if (StringConstant.ORG_GROUP.equals(user.getUserCategory())) {
            queryWrapper.lambda().in(BankAccountEntity::getEnterpriseId, enterpriseService.findCoreEnterPriseIds());
        } else {
            queryWrapper.lambda().eq(BankAccountEntity::getEnterpriseId, user.getEnterpriseId());
        }
        List<BankAccountEntity> bankAccounts = list(queryWrapper);
        if (CollectionUtils.isEmpty(bankAccounts)) {
            return new ArrayList<>();
        }
        return bankAccounts.stream().map(BankAccountEntity::getAccountOpeningOutlet).distinct().collect(Collectors.toList());
    }

    @Override
    public BankAccountEntity getByEnterpriseId(String enterpriseId) {
        QueryWrapper<BankAccountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BankAccountEntity::getEnterpriseId, enterpriseId)
                .eq(BankAccountEntity::getRegisterAccount, 1);
        return this.getOne(queryWrapper);
    }

    /**
     * 打款认证-企业打款认证查询
     *
     * @param user 用户
     * @return 银行信息
     */
    @Override
    public BankAccountEntity getBankAccount(User user) {
        QueryWrapper<BankAccountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BankAccountEntity::getEnterpriseId, user.getEnterpriseId());
        List<BankAccountEntity> list = this.list(queryWrapper);
        if (!ObjectUtils.isEmpty(list)) {
            return list.get(0);
        }
        return new BankAccountEntity();
    }

    /**
     * 查询银行账户下拉框
     *
     * @param user 用户信息
     * @return 银行
     */
    @Override
    public List<BankAccountEntity> getAccountList(User user) {
        QueryWrapper<BankAccountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BankAccountEntity::getEnterpriseId, user.getEnterpriseId())
                .eq(BankAccountEntity::getStopState, AccountStopStatusEnum.ACCOUNT_ENABLE.getCode());
        return this.list(queryWrapper);
    }

}
